package com.yf.compareYFJX;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yf.compareYFJX.JxModel.request.Goods;
import com.yf.compareYFJX.JxModel.request.RequQueryGoods;
import com.yf.compareYFJX.JxModel.response.getgoods.Data;
import com.yf.compareYFJX.JxModel.response.getgoods.JXGoodsResult;
import com.yf.compareYFJX.ecpModel.ResChannelGoods.ResGoodsResult;
import com.yf.compareYFJX.ecpModel.ResChannelGoods.Rows;
import com.yf.compareYFJX.ecpModel.UtilsModel.Openx;
import com.yf.compareYFJX.ecpModel.queryChannels.ChannelByChannelCode;
import com.yf.compareYFJX.ecpModel.queryChannels.ChannelsRequest;
import com.yf.compareYFJX.ecpModel.queryChannels.ChannelsResult;
import com.yf.compareYFJX.ecpModel.queryGoods.*;
import com.yf.compareYFJX.excelModel.DiffernEntity;
import com.yf.compareYFJX.excelModel.DiffernEntity2;
import com.yf.compareYFJX.test.DemoData;
import org.junit.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CompareApplication {

    /**
     * 查询ECP益丰精选的渠道商品接口
     * 测试：https://ecp-te.pharmacyyf.com/ecp-boss-new//openx/boss/channelGoodsService/listChannelGoodsByPage
     * 生产：https://ecp.yifengx.com/ecp-boss-new/openx/boss/channelGoodsService/listChannelGoodsByPage
     */
    private final static String ECPGOODSURI = "https://ecp.yifengx.com/ecp-boss-new/openx/boss/channelGoodsService/listChannelGoodsByPage";

    /**
     * 查询ECP益丰精选下所有子渠道的接口
     */
    private final static String ECPCHANNELSURI = "https://ecp.yifengx.com/ecp-boss-new/openx/boss/channelService/listChildrenChannelByTopCode";

    /**
     * 查询益丰精选下指定渠道的商品列表的接口
     * 测试：https://sop-te.yifengx.com/ssm-boss/cloudGoods/queryService/getGoodsList
     * 生产：https://sop.yifengx.com/ssm-boss/cloudGoods/queryService/getGoodsList
     */
    private final static String JXGETGOODS = "https://sop.yifengx.com/ssm-boss/cloudGoods/queryService/getGoodsList";

    /**
     * 益丰精选根据渠道编码查询某个渠道
     * 生产：https://sop.yifengx.com/ssm-rest/channel/queryService/getChannelByChannelCode
     *
     * @param args
     * @throws IOException
     */
    private final static String QUERYCHANNEL = "https://sop.yifengx.com/ssm-rest/channel/queryService/getChannelByChannelCode";


    public static void main(String[] args) throws Exception {

        System.out.println(new Date());
        //先从磁盘拿到openxhead的数据
        _openx_head openx_head = getOpenxHead();

        //1.查询ecp益丰精选下所有的渠道  生产渠道数：6013
        HttpUtils queryEcpChann = new HttpUtils(ECPCHANNELSURI, 5000, true);
        ChannelsRequest channelsRequest = new ChannelsRequest();
        channelsRequest.set_openx_head(openx_head);
        channelsRequest.setTopChannelCode("YFJX");
        String ECPchannels = queryEcpChann.post(JSONObject.toJSONString(channelsRequest));
        //拿到所有渠道集合
        List<ChannelsResult> channelsResults = JSONObject.parseArray(ECPchannels, ChannelsResult.class);

        //创建写入excel流
        String fileName = "F:\\yf\\work\\比对YFJX\\YFJXCompare\\YFJXDemo.xlsx";
        // 这里 需要指定写用哪个class去写
        ExcelWriter excelWriter = EasyExcel.write(fileName).build();
        //设定好sheet名称 ， 坑：先写入的sheet下标应该排序在前面，否则无法写入不同sheet
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "益丰精选商品差集").head(DiffernEntity.class).build();

        //设定好sheet2名称
        WriteSheet writeSheet2 = EasyExcel.writerSheet(1, "精选没有商品渠道集").head(DiffernEntity2.class).build();

        List<DiffernEntity2> chaDifs = new ArrayList<>();

        //try{}finally{}在finally中完成finnish()操作 可以在出现异常时将已经获取到的sheet写入excel
        try {
            //2.遍历每个渠道，拿到渠道编码，调用精选商城接口查询精选中是否有该渠道 --5
            for (int i = 6000; i < 6013; i++) {
                ChannelsResult channel = channelsResults.get(i);
                String channelCode = channel.getChannelCode();
                System.out.println("当前遍历：" + channelCode);
                //如果是YFJX 直接跳出此次循环
                if (channel.getChannelCode().equals("YFJX")) {
                    continue;
                }

                //调用精选商城接口查询精选中是否有该渠道
                HttpUtils queryTheChannel = new HttpUtils(QUERYCHANNEL, 5000, true);
                ChannelByChannelCode checkChannel = new ChannelByChannelCode();
                checkChannel.setChannelCode(channelCode);
                String checkResult = queryTheChannel.post(JSONObject.toJSONString(checkChannel));

                //3.如果精选商城不存在该渠道跳到下次循环，如果存在进行商品比对
                if (checkResult.equals("null")) {
                    System.out.println("渠道： " + channelCode + " 精选商城不存在");
                    continue;
                }

                //4.两个精选的商品比对，先查找ecp存在而精选不存在的商品
                // a.查询ecp益丰精选该子渠道商品列表
                //模拟请求参数
                ChannelGoods channelGoods = new ChannelGoods();
                channelGoods.setChannelCodes(channelCode);
                channelGoods.setChannelCode1("1个选中项");

                Page page = configPage(1, 100000);

                //openx----start
                _openx_head _openx_head = openx_head;
                //openx----end

                EcpYFJXBean ecpYFJXBean = new EcpYFJXBean();
                ecpYFJXBean.set_openx_head(_openx_head);
                ecpYFJXBean.setChannelGoods(channelGoods);
                ecpYFJXBean.setPage(page);

                System.out.println(JSONObject.toJSON(ecpYFJXBean));

                //调用查询ecp渠道商品接口
                HttpUtils httpClient = new HttpUtils(ECPGOODSURI, 50000, true);
                String result = httpClient.post(JSONObject.toJSONString(ecpYFJXBean));
                //System.out.println(result);
                ResGoodsResult queryResults = JSONObject.parseObject(result, ResGoodsResult.class);

                //如果该渠道下没有商品，跳过此次循环
                if (queryResults.getRows().size() == 0) {

                    System.out.println("该渠道下没有商品");
                    continue;
                }
                //调用查询益丰精选渠道商品接口
                //模拟益丰精选getGoodsList接口请求参数
                RequQueryGoods requQueryGoods = new RequQueryGoods();
                Goods goods = getJXQueryGoods(channelCode);
                requQueryGoods.setGoods(goods);
                requQueryGoods.set_openx_head(openx_head);
                requQueryGoods.setPage(page);
                System.out.println(JSONObject.toJSONString(requQueryGoods));
                //拿到该渠道 益丰精选下所有商品
                HttpUtils jxGoodsClient = new HttpUtils(JXGETGOODS, 50000, true);
                String jxGoodsResults = jxGoodsClient.post(JSONObject.toJSONString(requQueryGoods));
                JXGoodsResult jxGoodsResult = JSONObject.parseObject(jxGoodsResults, JXGoodsResult.class);
                //System.out.println(jxGoodsResults);

                //该渠道ecp有商品而精选没有商品
                if (jxGoodsResult.getCount() == 0) {
                    System.out.println("ecp有商品，精选没有的情况，渠道编号：" + channelCode + ",下标：" + i);
                    DiffernEntity2 chaDif = new DiffernEntity2();
                    chaDif.setChaanelCode(channelCode);
                    chaDifs.add(chaDif);
                    //写入精选没有商品的渠道集
                    excelWriter.write(chaDifs, writeSheet2);
                    continue;
                }
                List<Data> jxGoods = jxGoodsResult.getData();
                List<Rows> ecpJxGoods = queryResults.getRows();
                //用于比对精选的商品编码集合
                List<String> jxGCodes = new ArrayList<>();
                //用于比对ecp精选的商品编码集合
                List<String> ecpJxGCodes = new ArrayList<>();

                //装载差集的容器
                List<DiffernEntity> differnEntityList = new ArrayList<>();
                for (Data jxGood : jxGoods) {
                    jxGCodes.add(jxGood.getSpuCode());
                }

                //遍历ecp益丰精选当前渠道的所有商品
                for (int j = 0; j < ecpJxGoods.size(); j++) {
                    Rows currGood = ecpJxGoods.get(j);
                    String goodCode = currGood.getGoodsCode();
                    ecpJxGCodes.add(goodCode);
                    //System.out.println("当前遍历：渠道编码：" + channelCode + ",商品编码：" + goodCode + ",遍历下标" + j);
                    //ecp当前渠道的某一商品在益丰精选中不存在
                    if (!jxGCodes.contains(goodCode)) {
                        //System.out.println(" 精选缺失 -- 渠道编码：" + channelCode + ",商品编码：" + goodCode + ",遍历ECP下标" + j);
                        DiffernEntity differnEntity = new DiffernEntity();
                        differnEntity.setChannelName("精选缺失");
                        differnEntity.setChannelCode(channelCode);
                        differnEntity.setGoodCode(goodCode);
                        differnEntityList.add(differnEntity);
                    }
                    //System.out.println(jxGoodsResults);
                }

                //遍历益丰精选当前渠道的所有商品
                for (int k = 0; k < jxGoods.size(); k++) {
                    Data currGood = jxGoods.get(k);
                    String goodCode = currGood.getSpuCode();
                    //System.out.println("当前遍历：渠道编码：" + channelCode + ",商品编码：" + goodCode + ",遍历下标" + j);
                    //精选当前渠道的某一商品 在ECP益丰精选中不存在
                    if (!ecpJxGCodes.contains(goodCode)) {
                        //System.out.println(" ECP精选缺失 -- 渠道编码：" + channelCode + ",商品编码：" + goodCode + ",遍历精选下标" + k);
                        DiffernEntity differnEntity = new DiffernEntity();
                        differnEntity.setChannelName("ECP精选缺失");
                        differnEntity.setChannelCode(channelCode);
                        differnEntity.setGoodCode(goodCode);
                        differnEntityList.add(differnEntity);
                    }
                }

                //System.out.println(differnEntityList);
                //实现excel写的操作,写入精选商品差集
                System.out.println("写入excel商品差集,渠道编号：" + channelCode + ",下标：" + i);
                excelWriter.write(differnEntityList, writeSheet);

            }
        }
        finally {
            excelWriter.finish();
        }
    }

    /**
     * 益丰精选商品列表请求参数
     */
    private static Goods getJXQueryGoods(String channelCode) {
        //模拟益丰精选getGoodsList接口请求参数
        Goods goods = new Goods();
        ArrayList<String> channelCodes = new ArrayList<>();
        channelCodes.add(channelCode);

        goods.setChannelCodes(channelCodes);
        //goods.setSpuCode(goodCode);
        goods.setShelvesType("ALL");
        //测试：YD-5e79a51c28a3200001d9e719
        goods.setShopCode("YD-5e81e1c21e591400010c2ff9");
        //测试：5e79a51c28a3200001d9e719
        goods.setShopMerchant("5e81e1c21e591400010c2ff9");

        return goods;
    }

    /**
     * 配置请求的分页
     */
    private static Page configPage(int pageNum, int pageSize) {
        Page page = new Page();
        page.setOffset(0);
        page.setPageNum(pageNum);
        page.setPageSize(pageSize);
        page.setPageSizeZero(false);
        page.setCountSql(true);
        page.setIsExport(false);
        return page;
    }

    /**
     * 拿到请求参数openx_head
     *
     * @return
     */
    public static _openx_head getOpenxHead() throws Exception {
        File file = new File("F:\\yf\\work\\比对YFJX\\YFJXCompare\\openxhead.txt");
        FileReader fin = new FileReader(file);
        BufferedReader bre = new BufferedReader(fin);
        String s = bre.readLine();
        StringBuilder strb = new StringBuilder("");
        while (s != null) {
            //System.out.println(s);
            strb.append(s);
            s = bre.readLine();
        }
        String jsonData = strb.toString();
        fin.close();
        _openx_head openxhead = JSONObject.parseObject(jsonData, _openx_head.class);
        //System.out.println(openh.get_openx_head());
        return openxhead;
    }


    /**
     * 旧方式：拿到请求参数openx_head
     *
     * @return
     */
    private static _openx_head oldgetOpenxHead() {
        //openx----start
        _openx_head openx_head = new _openx_head();
        openx_head.setSessionId("47750477-0798-444E-A298-93B8BCCC0F5A");
        Merchant merchant = new Merchant();
        merchant.setAlias("益丰大药房");
        merchant.setCode("yfdyf");
        merchant.setContactIdNumber("432522198810041896");
        merchant.setContactPersonMobile("15900000001");
        merchant.setContactPersonName("超管");
        merchant.setId("5c49b2b72adc9100015f02ca");
        merchant.setIntro("湖南益丰大药房");
        merchant.setName("益丰大药房");
        openx_head.setMerchant(merchant);

        Token token = new Token();
        token.setAddress("175.6.17.66");
        token.setDevice("278afcf8-26cc-4958-b8af-27a955923aec");
        token.setSession("A9FE4769C5A47C72A8699C450E46C510");
        token.setUserCode("61770e7ce3fee50001e85e87");
        token.setUserName("黄俊捷");
        token.setUserToken("26f11ebb-2cdf-41e9-a5b5-48d3c799d496");
        openx_head.setToken(token);

        User user = new User();
        user.setCreateTime(new Long("1635192379000"));
        user.setId("61770e7ce3fee50001e85e87");
        user.setLogin(false);
        user.setMerchantId("5c49b2b72adc9100015f02ca");
        user.setMobile("18076712475");
        user.setNumber("00221679");
        user.setOrgId("5fae2a01c9571e0001b6b8be");
        user.setParentId("5fae2a01c9571e0001b6b8b6");
        user.setPost("JAVA工程师");
        user.setPostCode("10000605");
        user.setStatus("1");
        user.setUserName("黄俊捷");
        openx_head.setUser(user);

        openx_head.setAuth_token("937b94f8-956f-4f27-a6ad-9be2caab770a");
        openx_head.setUserCode("61770e7ce3fee50001e85e87");
        openx_head.setDevice("278afcf8-26cc-4958-b8af-27a955923aec");
        //openx----end
        return openx_head;
    }

    public static String getCode(String path) throws Exception {
        InputStream inputStream = new FileInputStream(path);
        byte[] head = new byte[3];
        inputStream.read(head);
        String code = "GBK"; // 或GBK
        if (head[0] == -1 && head[1] == -2)
            code = "UTF-16";
        else if (head[0] == -2 && head[1] == -1)
            code = "Unicode";
        else if (head[0] == -17 && head[1] == -69 && head[2] == -65)
            code = "UTF-8";
        inputStream.close();
        return code;
    }
}
